import React, { useState, useEffect } from "react";
import { Layout, Breadcrumb, Menu, Dropdown, Avatar, message } from "antd";
import { EditOutlined, TeamOutlined, MenuUnfoldOutlined, MenuFoldOutlined, ReadOutlined, SelectOutlined, CaretDownOutlined } from "@ant-design/icons";
// import { useNavigate } from "react-router-dom";
import logo from "./assets/images/logo.png";
import heaPortrait from "./assets/images/头像.jpg";
import "App.less";
import { Dispatch } from 'redux'
import { connect } from 'react-redux'

import { useLocation, useParams, Outlet, useNavigate, Link } from "react-router-dom";

const { Header, Footer, Sider, Content } = Layout;
const { SubMenu } = Menu;


interface IKey {
  key1: number;
  changekeyFn: () => void
}


function App(props: IKey) {
  // const navigate = useNavigate();
  const [visible, setVisible] = useState(false)
  const [avatar, setAvatar] = useState(heaPortrait)
  const [username, setUsername] = useState("匿名用户")
  const [bread, setBread] = useState("")

  const [asideKey, setasideKey] = useState('0')


  const loaction = useLocation() // 获取location，即可得到state中的参数
  let navigate = useNavigate()

  useEffect(() => {
    let avatar1 = process.env.SERVER_PORT + '/' + localStorage.getItem("avatar") || heaPortrait
    let username1 = localStorage.getItem("username") || '匿名用户'
    setAvatar(avatar1)
    setUsername(username1)

    if (loaction.pathname === '/') {
      navigate('/list')
    }

    switch (loaction.pathname) {
      case "/list":
        setasideKey("1");
        setBread('查看文章列表')
        break;
      case "/edit":
        setasideKey("2");
        setBread('文章编辑')
        break;
      case "/means":
        setasideKey("3");
        setBread('修改资料')
        break;
      case "/namelist":
        setasideKey("4");
        setBread('小编名单')
        break;
      case "/adminlist":
        setasideKey("5");
        setBread('管理员名单')
        break;
      default:
        setasideKey("0");
        break;
    }
    if (loaction.pathname.includes('/edit')) {
      setasideKey("2");
    }

  }, [loaction.pathname, props.key1])

  const params = useParams()     // 获取地址栏携带的参数xxx： /list/xxx

  const goMeans = () => {
    let token = localStorage.getItem("cms-token")
    if (token) {
      navigate('/means')
    } else {
      message.warning("登录失效,请重新登录", 1.5)
      setTimeout(() => {
        navigate('/login')
      }, 1500)
    }
  }

  const logout = () => {
    localStorage.removeItem("cms-token")
    localStorage.removeItem("avatar")
    message.success("即将跳转登录页", 1.5)
    setTimeout(() => {
      navigate('/login')
    }, 1500)
  }

  const menu = (
    <Menu>
      <Menu.Item key={1} onClick={goMeans}>修改资料</Menu.Item>
      <Menu.Divider />
      <Menu.Item onClick={logout} key={2}>退出登录</Menu.Item>
    </Menu>
  );

  const [collapsed, setCollapsed] = useState(false);

  return (
    <Layout>
      <Sider
        theme="dark"
        trigger={null} collapsible collapsed={collapsed}
        style={{
          overflow: "auto",
          height: "100vh",
          position: "fixed",
          left: 0,
        }}
      >
        <div className="logo" style={{ overflow: 'hidden' }}>
          <img src={logo} alt="" className="logoimg" />
          {!collapsed ? <span style={{ whiteSpace: 'nowrap' }} >CMS后台管理系统</span> : ''}
        </div>
        <Menu theme="dark" mode="inline" defaultSelectedKeys={[asideKey]} selectedKeys={[asideKey]}>
          <Menu.Item key="1" icon={<EditOutlined />}>
            <Link to="/list">查看文章列表</Link>
          </Menu.Item>
          <Menu.Item key="2" icon={<ReadOutlined />}>
            <Link to="/edit">文章编辑</Link>
          </Menu.Item>

          <Menu.Item key="3" icon={<ReadOutlined />}>
            <Link to="/means">修改资料</Link>
          </Menu.Item>
          <SubMenu key="sub2" icon={<TeamOutlined />} title={localStorage.getItem('player') === 'admin' ? '超级管理员' : '管理员'} style={{ display: localStorage.getItem('player') === 'vip' || localStorage.getItem('player') === 'admin' ? 'block' : 'none' }}>
            <Menu.Item key="4" icon={<SelectOutlined />}>
              <Link to="/namelist">小编名单</Link>
            </Menu.Item>

            <Menu.Item key="5" icon={<SelectOutlined />} style={{ display: localStorage.getItem('player') === 'admin' ? 'block' : 'none' }}>
              <Link to="/adminlist">管理员名单</Link>
            </Menu.Item>
          </SubMenu>
        </Menu>
      </Sider>
      {/* <button onClick={cangeusername}>修改username</button> */}

      <Layout>
        <Header className='header' style={{paddingLeft:!collapsed?'200px':'80px'}} key={props.key1} >
          <div className="header_left">
            {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
              className: 'trigger',
              onClick: () => setCollapsed(!collapsed),
            })}

            <Breadcrumb style={{ margin: "16px 0" }}>
              <Breadcrumb.Item>
                <Link to="/">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {bread}
              </Breadcrumb.Item>
            </Breadcrumb>
          </div>

          <Dropdown overlay={menu} onVisibleChange={() => setVisible(!visible)} visible={visible}>
            <a className="ant-dropdown-link" href="!#" onClick={(e) => e.preventDefault()}>
              <img className="avatar" src={avatar} alt="" />
              <span>{username}</span>
              <CaretDownOutlined />
            </a>
          </Dropdown>
        </Header>
        <Content style={{marginLeft:!collapsed?'200px':'80px'}} className="content" >
          <section className="content_main" >
            <Outlet  />
          </section>
        </Content>
      </Layout>
      {/* <Footer className="footer">Respect | Copyright © 2022 Author hanyu</Footer> */}
    </Layout>
  );
};

const mapStateToProps = (state: { key: number }) => {
  return {
    key1: state.key
  }
}

const mapDispatchToProps = (dispatch: Dispatch) => {
  return {
    changekeyFn() {
      dispatch({ type: 'changekey' })
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);
